package de.openlaboratory.elib.controller.listener;

import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import de.openlaboratory.elib.core.LogManager;
import de.openlaboratory.elib.database.hibernate.HibernateUtil;

public class HibernateListener implements ServletContextListener
{

	@Override
	public void contextInitialized(ServletContextEvent arg0)
	{
		HibernateUtil.getSessionFactory();
	}

	@Override
	public void contextDestroyed(ServletContextEvent arg0)
	{
		HibernateUtil.getSessionFactory().close();

		// This manually deregisters JDBC driver (Tomcat 7 redeploy issue)
		
		LogManager.logMessage("Shutdown: Getting Drivers...");
		
		Enumeration<Driver> drivers = DriverManager.getDrivers();
		while (drivers.hasMoreElements())
		{
			Driver driver = drivers.nextElement();
			try
			{
				DriverManager.deregisterDriver(driver);
				LogManager.logMessage(String.format("deregistering jdbc driver: %s", driver));
			}
			catch (SQLException e)
			{
				LogManager.logMessage(String.format("Error deregistering driver %s: %s", driver, e.getMessage()));
			}

		}
		LogManager.logMessage("JDBC Driver derigistration completed.");
	}
}
